# 使用MindIE官方镜像作为基础镜像
# 参考: https://www.hiascend.com/document/detail/zh/mindie/22RC1/quickstart/mindiesd_quickstart_0002.html
FROM swr.cn-south-1.myhuaweicloud.com/ascendhub/mindie:2.2.RC1-800I-A2-py311-openeuler24.03-lts

# 设置环境变量
ENV PYTHONUNBUFFERED=1
ENV LOG_LEVEL=INFO
ENV TORCH_DEVICE_BACKEND_AUTOLOAD=0

# 安装git（如果镜像中没有）
RUN yum install -y git curl wget

# 克隆Wan2.1代码到 /workspace
RUN mkdir -p /workspace && \
    cd /workspace && \
    git clone https://gitcode.com/yanlp/Wan2.1.git && \
    echo "✓ Wan2.1代码克隆完成" && \
    ls -la /workspace/Wan2.1/

# 安装Wan2.1依赖
RUN cd /workspace/Wan2.1 && \
    pip install --no-cache-dir -r requirements.txt && \
    echo "✓ Wan2.1依赖安装完成"

# 设置FastAPI工作目录
WORKDIR /app

# 设置PYTHONPATH（包含Wan2.1路径）
ENV PYTHONPATH=/app:/workspace/Wan2.1:$PYTHONPATH

# 安装FastAPI额外的Python依赖
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# 安装系统依赖（git、C/C++编译器、OpenGL库等）
# NPU算子JIT编译需要gcc和glibc-devel（提供stdio.h等头文件）
RUN yum install -y \
gcc gcc-c++ glibc-devel glibc-headers kernel-headers make \
mesa-libGL mesa-libGL-devel mesa-libGLU mesa-libGLU-devel libglvnd-glx 

# 复制FastAPI应用代码
COPY api/ ./api/
COPY config/ ./config/
COPY entrypoint.sh ./
COPY cat.png ./

# 创建必要的目录
RUN mkdir -p /app/inputs /app/outputs /app/temp /app/logs

# 设置权限
RUN chmod +x entrypoint.sh

# 验证安装
RUN echo "验证安装..." && \
    test -f /workspace/Wan2.1/generate.py && echo "✓ generate.py存在" && \
    python3 -c "import fastapi; print(f'✓ FastAPI {fastapi.__version__}')" && \
    echo "✓ 所有组件就绪"

# 暴露端口
EXPOSE 8000

# 健康检查
HEALTHCHECK --interval=60s --timeout=30s --start-period=180s --retries=3 \
    CMD curl -f http://localhost:8000/health || exit 1

# 启动命令
ENTRYPOINT ["/app/entrypoint.sh"]
